package com.smartcampusbackend.service.impl;

import com.smartcampusbackend.mapper.InterestCommunityMapper;
import com.smartcampusbackend.mapper.InterestCommunityMemberMapper;
import com.smartcampusbackend.mapper.UserMapper;
import com.smartcampusbackend.model.InterestCommunity;
import com.smartcampusbackend.model.InterestCommunityMember;
import com.smartcampusbackend.model.User;
import com.smartcampusbackend.service.InterestCommunityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class InterestCommunityServiceImpl implements InterestCommunityService {

    @Autowired
    private InterestCommunityMapper communityMapper;
    
    @Autowired
    private InterestCommunityMemberMapper memberMapper;
    
    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional
    public InterestCommunity createCommunity(InterestCommunity community, Integer creatorId) {
        // 获取用户信息
        User creator = userMapper.selectById(creatorId);
        if (creator == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 检查realName是否为空
        if (creator.getRealName() == null || creator.getRealName().trim().isEmpty()) {
            throw new RuntimeException("用户真实姓名不能为空，请完善个人信息");
        }
        
        // 设置创建信息
        community.setCreatorId(creatorId);
        community.setCreatorName(creator.getRealName().trim());
        community.setMemberCount(1);
        community.setPostCount(0);
        community.setCreateTime(LocalDateTime.now());
        community.setUpdateTime(LocalDateTime.now());
        
        // 保存社群
        communityMapper.insert(community);
        
        // 创建者自动加入社群
        InterestCommunityMember member = new InterestCommunityMember();
        member.setCommunityId(community.getId());
        member.setUserId(creatorId);
        member.setUserName(creator.getRealName().trim());
        member.setUserRole(creator.getRole());
        member.setJoinType("CREATOR");
        member.setJoinTime(LocalDateTime.now());
        member.setStatus(1);
        memberMapper.insert(member);
        
        return community;
    }

    @Override
    @Transactional
    public boolean deleteCommunity(Integer communityId, Integer userId, boolean isAdmin) {
        InterestCommunity community = communityMapper.selectById(communityId);
        if (community == null) throw new RuntimeException("社群不存在");
        if (!isAdmin && !community.getCreatorId().equals(userId)) {
            throw new RuntimeException("无权删除该社群");
        }
        // 删除社群及其成员等相关数据
        communityMapper.deleteById(communityId);
        // TODO: 如有成员表、消息等，需一并删除
        return true;
    }

    @Override
    public List<InterestCommunity> getCommunitiesByCategory(String category) {
        return communityMapper.findByCategory(category);
    }

    @Override
    public List<InterestCommunity> getAllCommunities() {
        return communityMapper.selectList(null);
    }

    @Override
    @Transactional
    public boolean joinCommunity(Integer communityId, Integer userId) {
        // 检查社群是否存在
        InterestCommunity community = communityMapper.selectById(communityId);
        if (community == null) {
            throw new RuntimeException("社群不存在或已删除");
        }
        
        // 检查用户是否已加入
        if (isUserJoined(communityId, userId)) {
            throw new RuntimeException("您已加入该社群");
        }
        
        // 获取用户信息
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 检查realName是否为空
        if (user.getRealName() == null || user.getRealName().trim().isEmpty()) {
            throw new RuntimeException("用户真实姓名不能为空，请完善个人信息");
        }
        
        // 添加成员
        InterestCommunityMember member = new InterestCommunityMember();
        member.setCommunityId(communityId);
        member.setUserId(userId);
        member.setUserName(user.getRealName().trim());
        member.setUserRole(user.getRole());
        member.setJoinType("MEMBER");
        member.setJoinTime(LocalDateTime.now());
        member.setStatus(1);
        memberMapper.insert(member);
        
        // 更新成员数量
        int memberCount = memberMapper.countByCommunityId(communityId);
        communityMapper.updateMemberCount(communityId, memberCount);
        
        return true;
    }

    @Override
    @Transactional
    public boolean leaveCommunity(Integer communityId, Integer userId) {
        // 检查社群是否存在
        InterestCommunity community = communityMapper.selectById(communityId);
        if (community == null) {
            throw new RuntimeException("社群不存在或已删除");
        }
        
        // 检查是否为创建者
        if (community.getCreatorId().equals(userId)) {
            throw new RuntimeException("创建者不能退出社群，请删除社群");
        }
        
        // 检查是否已加入
        InterestCommunityMember member = memberMapper.findByUserAndCommunity(userId, communityId);
        if (member == null) {
            throw new RuntimeException("您未加入该社群");
        }
        
        // 删除成员记录
        memberMapper.deleteById(member.getId());
        
        // 更新成员数量
        int memberCount = memberMapper.countByCommunityId(communityId);
        communityMapper.updateMemberCount(communityId, memberCount);
        
        return true;
    }

    @Override
    @Transactional
    public boolean removeCommunityMember(Integer communityId, Integer memberUserId, Integer operatorUserId, boolean isAdmin) {
        InterestCommunity community = communityMapper.selectById(communityId);
        if (community == null) throw new RuntimeException("社群不存在");
        // 只有管理员或社群创建者可以删除成员
        if (!isAdmin && !community.getCreatorId().equals(operatorUserId)) {
            throw new RuntimeException("无权操作");
        }
        // 创建者不能被删除
        if (community.getCreatorId().equals(memberUserId)) {
            throw new RuntimeException("不能删除社群创建者");
        }
        int affected = memberMapper.deleteByCommunityIdAndUserId(communityId, memberUserId);
        if (affected > 0) {
            // 更新成员数量
            int memberCount = memberMapper.countByCommunityId(communityId);
            communityMapper.updateMemberCount(communityId, memberCount);
            return true;
        } else {
            throw new RuntimeException("成员不存在或已被删除");
        }
    }

    @Override
    public List<InterestCommunity> getUserCreatedCommunities(Integer userId) {
        return communityMapper.findByCreatorId(userId);
    }

    @Override
    public List<InterestCommunity> getUserJoinedCommunities(Integer userId) {
        return communityMapper.findUserJoinedCommunities(userId);
    }

    @Override
    public List<InterestCommunityMember> getCommunityMembers(Integer communityId) {
        return memberMapper.findByCommunityId(communityId);
    }

    @Override
    public boolean isUserJoined(Integer communityId, Integer userId) {
        InterestCommunityMember member = memberMapper.findByUserAndCommunity(userId, communityId);
        return member != null && member.getStatus() == 1;
    }
} 